/* $RCSFile: HtmlEditorDataType.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/DataTypes/HtmlEditorDataType.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Globalization;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

using AddonNice.UI;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;
using AddonNice.Helpers;

namespace AddonNice.UI.DataTypes
{
	/// <summary>
	/// List of available HTML editors
	/// </summary>
	public class HtmlEditorDataType : ListDataType
	{
        const string StrDefEditor   =   "Telerik RadEditor";
        
        public HtmlEditorDataType()
		{
			InnerDataType = PropertiesDataType.List;
		}

		public static void AddEditorToSettings(SettingsDictionary editorSettings, SettingItemGroup group,string ExtGrpName) 
		{
            int startOrder                      =   1;
            foreach (SettingItem it in editorSettings.Values)
            {
                if (startOrder < it.Order)
                    startOrder                  =   it.Order + 1;
            }
			PortalSettings pS                   =   (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
            bool isSpecial                      =   ( group == SettingItemGroup.MODULE_SPECIAL_SETTINGS ) ||
                ( group == SettingItemGroup.MODULE_SPECIAL_SETTINGS2 ) ||
                ( group == SettingItemGroup.MODULE_SPECIAL_SETTINGS2 ) ;
			
            SettingItem Editor                  =   (isSpecial) ?  new SettingItemSpecial(StStr.Editor,new HtmlEditorDataType())
                                                            : new SettingItem(StStr.Editor,new HtmlEditorDataType());
                                                
			Editor.Order                        =   startOrder++;
			Editor.Group                        =   group;
            if ( isSpecial )
                ((SettingItemSpecial)Editor).ExtendedGroupName  =   ExtGrpName;
			Editor.EnglishName                  =   "Editor";
			Editor.Description                  =   "Select the Html Editor for Module";

			SettingItem ControlWidth            =   (isSpecial) ? new SettingItemSpecial(StStr.Width,new UnitDataType())
                                                            : new SettingItem(StStr.Width,new UnitDataType());
                                                     
			ControlWidth.Value                  =   "100%";
			ControlWidth.Order                  =   startOrder++;
			ControlWidth.Group                  =   group;
            if ( isSpecial )
                ((SettingItemSpecial)ControlWidth).ExtendedGroupName  =   ExtGrpName;
			ControlWidth.EnglishName            =   "Editor Width";
			ControlWidth.Description            =   "The width of editor control";

			SettingItem ControlHeight           =   (isSpecial) ? new SettingItemSpecial(StStr.Height,new UnitDataType())
                                                            : new SettingItem(StStr.Height,new UnitDataType()) ;
			ControlHeight.Value                 =   "400";
			ControlHeight.Order                 =   startOrder++;
			ControlHeight.Group                 =   group;
            if ( isSpecial )
                ((SettingItemSpecial)ControlHeight).ExtendedGroupName  =   ExtGrpName;
			ControlHeight.EnglishName           =   "Editor Height";
			ControlHeight.Description           =   "The height of editor control";

            SettingItem CrmGoogleTranslate      =   (isSpecial) ? new SettingItemSpecial(StStr.GoogleTranslate,new BooleanDataType())
                                                                    : new SettingItem(StStr.GoogleTranslate,new BooleanDataType());
            CrmGoogleTranslate.Value		    =	StStr.strTrue;
			CrmGoogleTranslate.Order		    =	startOrder++;
            CrmGoogleTranslate.Group            =   group;
            if ( isSpecial )
                ((SettingItemSpecial)CrmGoogleTranslate).ExtendedGroupName  =   ExtGrpName;
			CrmGoogleTranslate.Description	    =	"Uncheck this setting if your client has no internet access.";
            CrmGoogleTranslate.EnglishName	    =	"Use Google Translation";


            SettingItem ModuleImageFolder       =   null;
			if ( pS != null )
			{
				string imgPath	                =	Path2.WebPathCombine(pS.PortalFullPath,"images");
                BaseDataType imdt               =   new FolderDataType(HttpContext.Current.Server.MapPath(imgPath),StStr.DefaultImageFolder);
				ModuleImageFolder               =   (isSpecial) ? new SettingItemSpecial(StStr.MODULE_IMAGE_FOLDER,imdt)
                                                    : new SettingItem(StStr.MODULE_IMAGE_FOLDER,imdt);
				ModuleImageFolder.Value         =   StStr.DefaultImageFolder;
				ModuleImageFolder.Order         =   startOrder++;
				ModuleImageFolder.Group         =   group;
                if ( isSpecial )
                    ((SettingItemSpecial)ModuleImageFolder).ExtendedGroupName  =   ExtGrpName;
				ModuleImageFolder.EnglishName   =   "Default Image Folder";
				ModuleImageFolder.Description   =   "This folder is used for editor in this module to take and upload images";

				// Set the portal default values
				if (pS.CustomSettings != null) 
				{
					string str                  =   string.Empty;
                    if ( pS.CustomSettings.StringValue(StStr.SiteSettingsDefaultEditor,ref str) )
                        Editor.Value            =   str;
                    if ( pS.CustomSettings.StringValue(StStr.SiteSettingsEditorWidth, ref str))
                        ControlWidth.Value      =   str;
                    if ( pS.CustomSettings.StringValue(StStr.SiteSettingsEditorHeight, ref str))
                        ControlHeight.Value     =   str;
                    if ( pS.CustomSettings.StringValue(StStr.SiteSettingsDefaultImageFolder, ref str) )
                        ModuleImageFolder.Value =   str;
                    // If internet is unvailable globally fot portal , invalidate the translator
                    CrmGoogleTranslate.Value    =	pS.CustomSettings[StStr.SiteSettingsGoogleTranslate].ToString();
				}
			}

			editorSettings.Add(Editor.Key, Editor);
			editorSettings.Add(ControlWidth.Key, ControlWidth);
			editorSettings.Add(ControlHeight.Key, ControlHeight);
			editorSettings.Add(CrmGoogleTranslate.Key, CrmGoogleTranslate);
			if (  ModuleImageFolder != null   )
				editorSettings.Add(ModuleImageFolder.Key, ModuleImageFolder);
		}

        /// <summary>
        /// We try to set a default value here: Portal default value or static value
        /// </summary>
		protected override void InitializeComponents()
		{
			base.InitializeComponents();
			// Default
            if (string.IsNullOrEmpty(innerValue))
            {
                // Change the default value to Portal Default Editor Value ... if we are not in portal default editor setting
                if (HttpContext.Current != null && HttpContext.Current.Items[StStr.strPortalSettings] != null)
                {
                    PortalSettings pS   =   (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
                    if (pS.CustomSettings != null)
                    {
                        string str      =   string.Empty;
                        if (pS.CustomSettings.ContainsKey(StStr.SiteSettingsDefaultEditor) &&
                            !pS.CustomSettings[StStr.SiteSettingsDefaultEditor].DataType.Equals(this))
                            Val         =   pS.CustomSettings[StStr.SiteSettingsDefaultEditor].Value;
                    }
                }
                // if still not set use default static value
                if (string.IsNullOrEmpty(innerValue))
                    Val                 =   StrDefEditor;
            }
		}
        
		public override object DataSource
		{
			get
			{
				return "Plain Text;FCKEditor V2;FreeTextBox;Telerik RadEditor".Split(';');
			}
		}

		public override string Description
		{
			get
			{
				return "HtmlEditor List";
			}
		}

		public override string Val
		{
			get
			{
				return innerValue;
			}
			set
			{
                base.Val    =   value;
			}
		}

		private static string getFtbLanguage (string wLanguage) 
		{
			switch (wLanguage.Substring(wLanguage.Length - 2).ToLower())
			{
				case "en": return "en-US";
				case "us": return "en-US";
				case "es": return "es-ES";
				case "cn": return "zh-cn";
				case "cz": return "cz-CZ";
				case "fi": return "fi-fi";
				case "nl": return "nl-NL";
				case "de": return "de-de";
				case "il": return "he-IL";
				case "it": return "it-IT";
				case "jp": return "ja-JP";
				case "kr": return "ko-kr";
				case "no": return "nb-NO";
				case "pt": return "pt-pt";
				case "ro": return "ro-RO";
				case "ru": return "ru-ru";
				case "se": return "sv-se";
				case "tw": return "zh-TW";
				default: return "en-US";
			}
		}

        /// <summary>
        /// Used by all StdAuxPage which need editing
        /// </summary>
		public IHtmlEditor GetEditor(Control PlaceHolderHTMLEditor,StdAuxPage auxPage)
		{
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType GetEditor BEG StdAuxPage: {0}, ModuleID: {1}",auxPage.PageID,auxPage.ModuleID),DataTypeTraceSwitch.Sw.Info);
			SettingsDictionary settings = auxPage.moduleSettingsDic; // force module loading don't remove
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType GetEditor LoadedModules.Count: {0}",auxPage.LoadedModules.Count),DataTypeTraceSwitch.Sw.Info);
			return GetEditor(PlaceHolderHTMLEditor, auxPage.ModuleID,settings,auxPage.portalSettings,false);
		}
		
        /// <summary>
        /// Used by HtmlStringDataType
        /// </summary>
        public IHtmlEditor GetEditor(Control PlaceHolderHTMLEditor,PortalModuleControl module)
		{
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType GetEditor BEG module: {0}",module.ModuleID),DataTypeTraceSwitch.Sw.Info);
			SettingsDictionary settings             =   module.Settings;
			return GetEditor(PlaceHolderHTMLEditor,module.ModuleID,settings,module.portalSettings,false);
		}

        public IHtmlEditor GetEditor(Control PlaceHolderHTMLEditor,PortalModuleControl module,bool rdOnly)
		{
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType GetEditor BEG module: {0}, ReadOnly: {1}",module.ModuleID,rdOnly),DataTypeTraceSwitch.Sw.Info);
			SettingsDictionary settings             =   module.Settings;
			return GetEditor(PlaceHolderHTMLEditor,module.ModuleID,settings,module.portalSettings,rdOnly);
		}
        
        private IHtmlEditor GetEditor(Control PlaceHolderHTMLEditor, int moduleID, SettingsDictionary settings, PortalSettings portalSettings,bool rdOnly)
        {
   			string edtName		                    =   string.Empty;
   			if ( settings.ContainsKey(StStr.Editor) )
                edtName                             =   settings[StStr.Editor].ToString();
            if ( edtName == string.Empty )
                edtName		                        =   portalSettings.CustomSettings[StStr.SiteSettingsDefaultEditor].ToString();
            // install the editor name before getEditor
            Val                                     =   edtName;

            IHtmlEditor EditorCtl                   =   null;
			string moduleImageFolder                =   settings[StStr.MODULE_IMAGE_FOLDER].ToString();
            string fullImagePath                    =   portalSettings.PhysicalToVirtualPath(settings[StStr.MODULE_IMAGE_FOLDER].FullPath);
            if (moduleImageFolder == string.Empty)
            {
                moduleImageFolder                   =   portalSettings.CustomSettings[StStr.SiteSettingsDefaultImageFolder].ToString();
                fullImagePath                       =   portalSettings.DefaultImageVirtualPath;
            }

            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType GetEditor BEG Val: {0}, ImageFolder: {1}",Val,moduleImageFolder),DataTypeTraceSwitch.Sw.Info);

            // Grabs ID from the place holder so that a unique editor is on the page if more than one
			// But keeps same ID so that the information can be submitted to be saved. [CDT]
			string uniqueID                             =   PlaceHolderHTMLEditor.ID;

			switch(Val)
			{
				case "FCKEditor V2": 
					FCKTextBoxV2 fckv2                  =   new FCKTextBoxV2();
					fckv2.ImageFolder                   =   moduleImageFolder;
					fckv2.BasePath                      =   Path2.ToAbsolute(Config.PortalFCKEditorPath);
					fckv2.AutoDetectLanguage            =   true;
					fckv2.DefaultLanguage               =   portalSettings.PortalUILanguage.Name.Substring(0,2);
					// CS 21/2/7 to replace with skin fckv2.EditorAreaCSS = portalSettings.GetCurrentTheme().CssFile;
					fckv2.ID                            =   string.Concat("FCKTextBox_", uniqueID);
					string conector                     =   Path2.ApplicationRootPath("/app_support/FCKconnectorV2.aspx");
					fckv2.ImageBrowserURL               =   Path2.ToAbsolute(Config.PortalFCKEditorPath)+"editor/filemanager/browser/default/browser.html?Type=Image&Connector=" + conector;
					fckv2.LinkBrowserURL                =   Path2.ToAbsolute(Config.PortalFCKEditorPath)+"editor/filemanager/browser/default/browser.html?Connector=" + conector;
					EditorCtl = ((IHtmlEditor) fckv2);
					break;
                case "Telerik RadEditor":
                    TelerikEditor rEdt                  =   new TelerikEditor();
                    rEdt.AutoResizeHeight               =   false;
                    rEdt.ID                             =   string.Concat("RadEditorTextBox_",uniqueID);
                    string[] SupportedLanguages         =   PortalSettings.SpellCheckerCultures;
                    foreach ( string dicLang in SupportedLanguages )
                        rEdt.Languages.Add(new SpellCheckerLanguage(dicLang,new CultureInfo(dicLang).DisplayName));
                    string[] folderPath                 =   new string[] { fullImagePath };
                    rEdt.ImageManager.ViewPaths         =   folderPath;
                    rEdt.ImageManager.UploadPaths       =   folderPath;
                    rEdt.ImageManager.DeletePaths       =   folderPath;

                    folderPath                          =   new string[] { portalSettings.DefaultMediaVirtualPath };
                    rEdt.MediaManager.ViewPaths         =   folderPath;
                    rEdt.MediaManager.UploadPaths       =   folderPath;
                    rEdt.MediaManager.DeletePaths       =   folderPath;

                    folderPath                          =   new string[] { portalSettings.DefaultFlashVirtualPath };
                    rEdt.FlashManager.ViewPaths         =   folderPath;
                    rEdt.FlashManager.UploadPaths       =   folderPath;
                    rEdt.FlashManager.DeletePaths       =   folderPath;

                    folderPath                          =   new string[] { portalSettings.DefaultSilverlightVirtualPath };
                    rEdt.SilverlightManager.ViewPaths   =   folderPath;
                    rEdt.SilverlightManager.UploadPaths =   folderPath;
                    rEdt.SilverlightManager.DeletePaths =   folderPath;

                    folderPath                          =   new string[] { portalSettings.DefaultDocumentVirtualPath };
                    rEdt.DocumentManager.ViewPaths      =   folderPath;
                    rEdt.DocumentManager.UploadPaths    =   folderPath;
                    rEdt.DocumentManager.DeletePaths    =   folderPath;

                    folderPath                          =   new string[] { portalSettings.DefaultTemplateVirtualPath };
                    rEdt.TemplateManager.ViewPaths      =   folderPath;
                    rEdt.TemplateManager.UploadPaths    =   folderPath;
                    rEdt.TemplateManager.DeletePaths    =   folderPath;
                    
                    rEdt.Load                           +=  new EventHandler(rEdt_Load);

                    if ( rdOnly )
                        rEdt.Enabled                    =   false;

                    EditorCtl                           =   ( (IHtmlEditor)rEdt );
                    break;
				
                case "FreeTextBox":
					FreeTextBox freeText                =   new FreeTextBox();
					freeText.ToolbarLayout              =   "ParagraphMenu,FontFacesMenu,FontSizesMenu,FontForeColorPicker,FontBackColorPicker,FontForeColorsMenu|Bold,Italic,Underline,Strikethrough;Superscript,Subscript,RemoveFormat;CreateLink,Unlink|JustifyLeft,JustifyRight,JustifyCenter,JustifyFull;BulletedList,NumberedList,Indent,Outdent;InsertRule|Delete,Cut,Copy,Paste;Undo,Redo,Print;InsertTable,InsertTableColumnAfter,InsertTableColumnBefore,InsertTableRowAfter,InsertTableRowBefore,DeleteTableColumn,DeleteTableRow,InsertImageFromGallery";
					freeText.ImageGalleryUrl            =   Path2.WebPathCombine(Path2.ApplicationRoot, "app_support/ftb.imagegallery.aspx?rif={0}&cif={0}&mID=" + moduleID.ToString());
					freeText.ImageFolder                =   moduleImageFolder;
					freeText.ImageGalleryPath           =   Path2.WebPathCombine(portalSettings.PortalFullPath, freeText.ImageFolder);
					freeText.ID                         =   string.Concat("FreeText_", uniqueID);
					freeText.Language                   =   getFtbLanguage (portalSettings.PortalUILanguage.Name);
					EditorCtl                           =   ((IHtmlEditor) freeText);
					break;

				case "Plain Text" :
				default :
					EditorCtl                           =   new TextEditor();
                    if ( rdOnly )
                        ((TextEditor)EditorCtl).Enabled =   false;
					break;
			}
            EditorCtl.Width                             =   settings[StStr.Width].ToUnit();
            EditorCtl.Height                            =   settings[StStr.Height].ToUnit();
			
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType GetEditor END Width: {0}, Height: {1}",EditorCtl.Width,EditorCtl.Height),DataTypeTraceSwitch.Sw.Info);
            PlaceHolderHTMLEditor.Controls.Add(((Control) EditorCtl));
			return EditorCtl;
		}

        /// <summary>
        /// Install the translation dropdown in editor on Load
        /// </summary>
        void rEdt_Load(object sender,EventArgs e)
        {
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType rEdt_Load BEG sender: {0}.",sender),DataTypeTraceSwitch.Sw.Info);
            if ( sender is RadEditor )
            {
                RadEditor e1                        =   (RadEditor)sender;
                if ( e1.Page is StdAuxPage )
                {
                    StdAuxPage pg                   =   (StdAuxPage)e1.Page;
                    if ( ( pg.moduleSettingsDic != null ) && pg.moduleSettingsDic.ContainsKey(StStr.GoogleTranslate) && pg.moduleSettingsDic[StStr.GoogleTranslate].ToBool())
                    {
                        if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HTMLEditorDataType rEdt_Load Adding translation: {0}.",sender),DataTypeTraceSwitch.Sw.Info);
                        e1.OnClientCommandExecuting =   "OnClientCommandExecuting";
                        // Add and fill the translate editor tool 
                        EditorDropDown ddn          =   new EditorDropDown("TranslateTool");
                        ddn.Text                    =   LocalizeHelper.Localize("EDITOR_TRANSLATE","Translate");
                        ddn.Width                   =   new Unit("130px");
                        e1.EnsureToolsFileLoaded();
                        e1.Tools[0].Tools.Insert(0,ddn);
                        string[] SupportedLanguages =   PortalSettings.SpellCheckerCultures;
                        foreach ( string dicLang in SupportedLanguages )
                        {
                            EditorDropDownItem it   =   new EditorDropDownItem(new CultureInfo(dicLang).DisplayName,dicLang.Substring(0,2));
                            ddn.Items.Add(it);
                        }
                    }
                }
            }
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]HTMLEditorDataType rEdt_Load END.",DataTypeTraceSwitch.Sw.Info);
        }
	}
}